﻿using FitnessCenter.DataAccessLayer.DataProviders;
using FitnessCenter.DataAccessLayer.Repositories.Interfaces;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

namespace FitnessCenter.DataAccessLayer.Repositories.Implementations
{
    public abstract class BaseRepository<T> : IRepository<T> where T : class
    {
        private FitnessCenterDataProvider DataModel { get; set; }
        protected DbSet<T> DataSet { get; private set; } 

        protected BaseRepository()
        {
            DataModel = new FitnessCenterDataProvider();
            DataSet = DataModel.Set<T>();
        }

        public IEnumerable<T> GetAll()
        {
            return DataSet;
        }

        public T GetByID<TKey>(TKey id)
        {
            return DataSet.Find(id);
        }

        public IEnumerable<T> GetByPredicate(Func<T, bool> predicate)
        {
            return DataSet.Where(predicate);
        }

        public void Save(T model)
        {
            if(IsExists(model))
                Update(model);
            else
                Add(model);

            SaveChanges();
        }

        public void Delete(T model)
        {
            DataSet.Remove(model);
            SaveChanges();
        }

        private void Update(T model)
        {
            DataSet.Attach(model);
            SaveChanges();
        }

        private void Add(T model)
        {
            DataSet.Add(model);
            SaveChanges();
        }

        private void SaveChanges()
        {
            DataModel.SaveChanges();
        }

        private bool IsExists(T model)
        {
            return DataSet.Contains(model);
        }
    }
}
